package com.wcs.exam.common.server.sms.impl;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.wcs.exam.common.server.sms.Sms;
import com.wcs.exam.common.server.sms.SmsFace;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 腾讯云
 *
 * @author wcs
 */
@Slf4j
@Component(value = "tencentSms")
public class TencentYunSmsImpl implements SmsFace {

    @Override
    public Boolean sendVerCode(String mobile, String code, Sms sms) {
        return tencent(mobile, sms.getTencentSmsSdkAppId(), new String[]{code}, sms.getTencentSmsSignName(), sms.getTencentSmsAuthCode(), sms.getTencentSmsAccessKeyId(), sms.getTencentSmsAccessKeySecret());
    }

    /**
     * 参考 <a href="https://cloud.tencent.com/document/product/382/43194#.E5.8F.91.E9.80.81.E7.9F.AD.E4.BF.A1">参考文档</a>
     */
    private static Boolean tencent(String phone, String smsSdkAppId, String[] templateParamSet, String signName, String templateId, String accessKeyId, String accessKeySecret) {
        Credential cred = new Credential(accessKeyId, accessKeySecret);
        SmsClient client = new SmsClient(cred, "ap-guangzhou");
        SendSmsRequest req = new SendSmsRequest();
        req.setSmsSdkAppId(smsSdkAppId);
        req.setSignName(signName);
        req.setTemplateId(templateId);
        req.setTemplateParamSet(templateParamSet);
        req.setPhoneNumberSet(new String[]{phone});
        try {
            SendSmsResponse res = client.SendSms(req);
            if (!"OK".equalsIgnoreCase(res.getSendStatusSet()[0].getCode())) {
                log.error("短信发送错误={}，手机号={}，templateParam={}", res.getSendStatusSet()[0].getMessage(), phone, templateParamSet);
                return false;
            }
            return true;
        } catch (Exception e) {
            log.error("系统异常", e);
            return false;
        }
    }
}
